﻿using LuaInterface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

/// <summary>
/// Lua接口
/// </summary>
namespace Common.LuaEngine
{
    /// <summary>
    /// Lua函数描述特性类
    /// </summary>
    public class MapleFunction : Attribute
    {
        private String FunctionName;

        public MapleFunction(String strFuncName)
        {
            FunctionName = strFuncName;
        }

        public String getFuncName()
        {
            return FunctionName;
        }
    }

    /// <summary>
    /// lua解释器
    /// </summary>
    public class MapleLuaEngine
    {

        private Lua pLuaVM = null;//lua虚拟机

        /// <summary>
        /// 注册lua函数
        /// </summary>
        /// <param name="pLuaAPIClass">lua函数类</param>
        public void BindLuaApiClass(Object pLuaAPIClass)
        {
            foreach (MethodInfo mInfo in pLuaAPIClass.GetType().GetMethods())
            {
                foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo))
                {
                    //LuaInterface.Lua
                    if (attr is MapleFunction)
                    {
                        string LuaFunctionName = (attr as MapleFunction).getFuncName();
                        Console.WriteLine("注册:{0}", LuaFunctionName);
                        pLuaVM.RegisterFunction(LuaFunctionName, pLuaAPIClass, pLuaAPIClass.GetType().GetMethod(LuaFunctionName));
                    }
                }
            }
        }


        public MapleLuaEngine()
        {
            if (pLuaVM == null)
            {
                pLuaVM = new Lua();
            }
        }

        /// <summary>
        /// 停止执行Lua脚本
        /// </summary>
        public void Stop()
        {
            pLuaVM.Dispose();
            pLuaVM.Close();
        }


        /// <summary>
        /// 加载脚本文件
        /// </summary>
        /// <param name="FilePath"></param>
        public void LoadFile(string FilePath) 
        {
            try
            {                
                pLuaVM.DoFile(FilePath);
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public object[] Invoking(string FunctionName, params object[] args)
        {
            object[] ret = null;

            if (pLuaVM.GetFunction(FunctionName) != null)
            {
                ret = pLuaVM.GetFunction(FunctionName).Call(args);
            }
            else
            {
                throw new Exception("找不到函数!");
            }

            return ret;
        }

    }
}
